from fastapi import APIRouter, HTTPException, Depends
from typing import List
from sqlalchemy.orm import Session
from schema import Sensor_schema
from controller import Sensor_controller
from database.db_init import get_db


router = APIRouter()


@router.post("/Sensor", response_model=Sensor_schema.Sensor, tags=["Sensor"])
async def create_Sensor(Sensor: Sensor_schema.Sensor, db: Session = Depends(get_db)):
    return Sensor_controller.create_Sensor(db, Sensor)


@router.get("/Sensor/{ID}", response_model=Sensor_schema.Sensor, tags=["Sensor"])
async def get_Sensor(ID: int, db: Session = Depends(get_db)):
    db_Sensor = Sensor_controller.get_Sensor(db, ID)
    if db_Sensor is None:
        raise HTTPException(status_code=404, detail="Sensor not found")
    return db_Sensor


@router.get("/Sensor", response_model=List[Sensor_schema.Sensor], tags=["Sensor"])
async def get_all_Sensor(db: Session = Depends(get_db)):
    all_db_Sensor = Sensor_controller.get_all_Sensor(db)
    if all_db_Sensor is None:
        raise HTTPException(status_code=404, detail="0 Sensor found, empty table")
    return all_db_Sensor


@router.put("/Sensor/{ID}", tags=["Sensor"])
async def update_Sensor(ID: int, field_name: str, field_value: str, db: Session = Depends(get_db)):
    try:
        db_Sensor = Sensor_controller.update_Sensor(db, ID, field_name, field_value)
        if db_Sensor is None:
            raise HTTPException(status_code=404, detail="Sensor not found")
        return db_Sensor
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error))


@router.delete("/Sensor/{ID}", tags=["Sensor"])
async def delete_Sensor(ID: int, db: Session = Depends(get_db)):
    is_deleted = Sensor_controller.delete_Sensor(db, ID)
    if is_deleted is None:
        raise HTTPException(status_code=404, detail=f'Sample {ID} does not exist in database')
    else:
        return {'message': f'Successfully delete sample {ID}'}
